<!--
 * @Description: 创建秒杀时间弹窗
 * @Author: liyujie
 * @Date: 2021/8/20
 * @Last Modified by: liyujie
 * @Last Modified time: 2021/8/20
-->
<template>
    <section class="wrapper">
        <el-dialog
            title="创建秒杀时间"
            :visible.sync="dialogVisible"
            width="600px"
            :close-on-click-modal="false"
            @close="beforeClose"
        >
            <div class="dialog-content">
                <el-form
                    :model="ruleForm"
                    :rules="rules"
                    label-width="100px"
                    ref="ruleForm"
                >
                    <el-form-item
                        label="选择日期"
                        prop="activeData"
                    >
                        <el-date-picker
                            v-model="ruleForm.activeData"
                            placeholder="选择秒杀日期"
                            type="date"
                            size="medium"
                            style="width: 400px"
                            value-format="timestamp"
                            :picker-options="pickerOptions"
                            @change="selectActiveTime"
                        />
                    </el-form-item>
                    <el-form-item
                        label="选择时间"
                        prop="activeTime"
                    >
                        <el-time-picker
                            is-range
                            v-model="ruleForm.activeTime"
                            size="medium"
                            :clearable="false"
                            range-separator="-"
                            start-placeholder="开始时间"
                            end-placeholder="结束时间"
                            placeholder="选择时间范围"
                            format='HH:mm'
                            value-format="timestamp"
                            style="width: 400px"
                            :disabled="!ruleForm.activeData"
                            @change="selectActiveTime"
                        />
                    </el-form-item>
                    <div>
                        <el-tag
                            v-for="(tag,index) in createTimeList"
                            :key="index"
                            closable
                            style="margin-left: 12px;margin-bottom: 12px"
                            @close="handleTagClose(index)"
                        >
                            {{ tag.label }}
                        </el-tag>
                    </div>
                    <el-form-item
                        label-width="0"
                        style="display: flex; justify-content: center;margin-bottom: 0; margin-top: 12px"
                    >
                        <el-button
                            size="medium"
                            style="width: 100px"
                            @click="close"
                        >
                            取消
                        </el-button>
                        <el-button
                            type="primary"
                            size="medium"
                            style="width: 100px;margin-left: 50px"
                            :loading="loading"
                            @click="handleSubmit()"
                        >
                            确定
                        </el-button>
                    </el-form-item>
                </el-form>
            </div>
        </el-dialog>
    </section>
</template>

<script>
import Vue from "vue";

const Dialog = {
    name: "CreateSeckillTime",
    props: {},
    data() {
        return {
            dialogVisible: false,
            loading: false,
            ruleForm: {
                activeData: '',
                activeTime: ''
            },
            rules: {
                activeData: [
                    {required: true, message: '请选择秒杀日期', trigger: 'blur'}
                ],
                activeTime: [
                    {required: true, message: '请选择秒杀时间', trigger: 'blur'}
                ]
            },
            createTimeList: [],
            pickerOptions: {
                disabledDate(time) {
                    return time.getTime() < new Date(new Date().setHours(0, 0, 0, 0));
                }
            },
        };
    },
    mounted() {

    },
    methods: {

        /**
         * 显示弹窗
         */
        show() {
            this.dialogVisible = true;
        },

        /**
         * 显示弹窗
         */
        close() {
            this.dialogVisible = false;
        },

        /**
         * 关闭弹窗前
         */
        beforeClose() {
            this.createTimeList.length = 0;
            this.ruleForm.activeTime = '';
            this.ruleForm.activeData = '';
            this.$emit('close');
        },

        /**
         * 选择秒杀时间
         */
        selectActiveTime() {
            if(!this.ruleForm.activeTime) {
                return;
            }

            this.$refs['ruleForm'].validate((valid) => {
                if (valid) {
                    let nowTime = this.$moment().startOf('day').format('x');
                    let start = this.ruleForm.activeTime[0] + this.ruleForm.activeData - Number(nowTime);
                    let end = this.ruleForm.activeTime[1] + this.ruleForm.activeData - Number(nowTime);
                    let labelStart = this.$moment(start).format('YYYY/MM/DD HH:mm');
                    let labelEnd = this.$moment(end).format('YYYY/MM/DD HH:mm');

                    start = Number(this.$moment(labelStart).format('x'));
                    end = Number(this.$moment(labelEnd).format('x'));
                    this.createTimeList.push({
                        value: [start / 1000, end / 1000],
                        label: `${labelStart} - ${labelEnd}`
                    });

                }
            });
        },

        /**
         * 移除秒杀时间
         */
        handleTagClose(index) {
            this.createTimeList.splice(index, 1);
        },

        /**
         * 创建活动时间
         */
        handleSubmit() {
            let indexError = 0, indexSuccess = 0;

            this.$refs.ruleForm.validate((valid) => {
                if (valid) {
                    this.loading = true;
                    let promiseList = this.createTimeList.map(item => {
                        return new Promise((resolve, reject) => {
                            this.$post('/student/shop_goods_flash_sale%5Cadd_time', {
                                start_time: item.value[0],
                                end_time: item.value[1]
                            }, resp => {
                                if (resp.code === 1) {
                                    indexSuccess++;
                                } else {
                                    indexError++;
                                }
                                resolve(resp);
                            });
                        });
                    });

                    // 请求完成
                    Promise.all(promiseList).then(res => {
                        console.log(indexError, indexSuccess, res);
                        if(indexError === 0) {
                            this.$notify({
                                title: '提示',
                                type: 'success',
                                message: '操作成功'
                            });
                        } else {
                            this.$message({
                                message: `创建失败个数${indexError}个`,
                                duration: 2000,
                                type: 'warning'
                            });
                            this.$notify({
                                title: '提示',
                                message: res[0].msg,
                                duration: 2000,
                                type: 'warning'
                            });
                        }

                        this.loading = false;
                        if(indexError !== promiseList.length) {
                            this.$emit('confirm', true);
                        }
                    });
                }
            });
        },
    }
};

export default Dialog;

const createSeckillTimeDialog = function (config) {
    return new Promise((resolve) => {
        const DialogConstructor = Vue.extend(Dialog);
        const instance = new DialogConstructor({
            propsData: config,
        }).$mount();

        instance.$on("close", function () {
            setTimeout(() => {
                document.body.removeChild(instance.$el);
                instance.$destroy();
            }, 300);
            resolve(false);
        });
        instance.$on("confirm", function (data) {
            instance.close();
            resolve(data);
        });
        document.body.appendChild(instance.$el);
        instance.dialogVisible = true;
    });
};

export { createSeckillTimeDialog };
</script>

<style scoped lang="less">
.dialog-content {

}
.dialog-footer {

}
/deep/ .el-dialog__header {
    padding-top: 10px;
    box-shadow:0 1px 0 0 rgba(233,233,233,1);
    display: flex;
    align-items: center;
    background: #FAFAFA;
    border-radius: 4px 4px 0 0;
    .el-dialog__title {
        font-weight: 500;
        color: #333;
        font-size: 14px;
    }
    .el-icon-close:before {
        color: rgb(194,194,194);
        font-size: 17px;
        font-weight: bold;
    }
    .el-dialog__headerbtn {
        top: 14px;
    }
}
/deep/ .el-dialog__body {
    padding: 24px 32px;
}
/deep/ .el-dialog {
    margin-top: 10vh!important;
}
</style>
